package com.qianfeng.zhangwei.touchevent;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;

/**
 *
 */
public class GestureActivity extends AppCompatActivity {
    private static final String TAG = "GestureActivity";
    private GestureDetector gestureDetector;
    private MySiginGestureLinstener mySiginGestureLinstener;
    private ImageView img;
    private int[] imageResId = {R.mipmap.hehe1, R.mipmap.hehe2, R.mipmap.hehe3, R.mipmap.hehe4};

    private int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture);
        img = (ImageView) this.findViewById(R.id.imageView);
        img.setImageResource(imageResId[index]);

        //第一步初始化 手势识别类
        /**
         * 参数1 上下文
         * 参数  OnGestureListener 接口
         */
        mySiginGestureLinstener = new MySiginGestureLinstener();
        gestureDetector = new GestureDetector(this, mySiginGestureLinstener);


    }

    /**
     * 第二步重写 onTouchEvent gestureDetector.onTouchEvent(event)
     *
     * @param event
     * @return
     */


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    public class MySiginGestureLinstener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return super.onDown(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            int startX = (int) e1.getX();
            int endX = (int) e2.getX();
            int startY = (int) e1.getY();
            int endY = (int) e2.getY();
            int distanceX = Math.abs(startX - endX);
            int distanceY = Math.abs(startY - endY);
            if (distanceX > distanceY) {
                index++;
                if (index < 4) {
                    img.setImageResource(imageResId[index]);
                }
            }


            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }


}
